package quotation.web.kvStore.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import quotation.enums.KvStoreEnum;
import quotation.web.kvStore.ddd.entity.KvEntity;
import quotation.web.kvStore.ddd.form.AddKvForm;
import quotation.web.kvStore.ddd.form.UpdateKvForm;
import quotation.web.kvStore.mapper.KvMapper;
import quotation.web.kvStore.service.KvService;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class KvServiceImpl extends ServiceImpl<KvMapper, KvEntity> implements KvService {

    @Override
    public List<KvStoreEnum> getAllEnum(String group) {
        List<KvStoreEnum> byGroup = KvStoreEnum.getByGroup(group);
        return byGroup;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(AddKvForm form) {
        KvEntity kvEntity = BeanUtil.copyProperties(form, KvEntity.class);
        this.save(kvEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(UpdateKvForm form) {
        KvEntity kvEntity = BeanUtil.copyProperties(form, KvEntity.class);
        this.saveOrUpdate(kvEntity);
    }

    @Override
    public List<KvEntity> getAllKv(String group) {

        List<KvStoreEnum> byGroup = KvStoreEnum.getByGroup(group);

        List<KvEntity> list = this.lambdaQuery()
                .eq(StrUtil.isNotEmpty(group), KvEntity::getKGroup, group)
                .list();

        Map<String, String> collect = list.parallelStream().collect(Collectors.toMap(KvEntity::getK, KvEntity::getDefaultValue));
        byGroup.forEach(kvStoreEnum -> {
            if (!collect.containsKey(kvStoreEnum.getKey())) {
                KvEntity kvEntity = new KvEntity(kvStoreEnum.getGroup(), kvStoreEnum.getKey(), kvStoreEnum.getDefaultValue(), kvStoreEnum.getDescribe());
                list.add(kvEntity);
            }
        });

        return list;
    }

    /**
     * 入参固定位枚举，实现默认值获取
     * {@link KvStoreEnum}
     */
    @Override
    public String getOrDefault(KvStoreEnum kvStoreEnum) {

        //todo 后续考虑添加缓存，单查询速度足够快

        KvEntity one = this.lambdaQuery()
                .eq(KvEntity::getK, kvStoreEnum.getKey())
                .one();

        if (ObjectUtil.isNotNull(one)) {
            return one.getDefaultValue();
        } else {
            return kvStoreEnum.getDefaultValue();
        }
    }

}
